#include "snapshottemp.h"
#include<QPixmap>
#include<QPainter>
#include<QScreen>
#include<QDesktopWidget>
#include<QApplication>
#include<QGuiApplication>
#include "log.h"
#include <QShowEvent>
#include <QPaintEvent>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QClipboard>
#include "globalmgr.h"
#include "snapshot.h"
#include "appcontroller.h"

#define LIMIT_WIDTH 50.0f       //限制宽高
#define LIMIT_HEIGHT 50.0f

SnapShotTemp::SnapShotTemp(QWidget *parent) : QWidget(parent)
  , bFinish(false)
{
    //截取桌面快照
    QDesktopWidget * pDesktoWidget = QApplication::desktop();
    QRect screenRect = pDesktoWidget->screenGeometry();
    this->setGeometry(screenRect);
    QScreen * pqscreen  = QGuiApplication::primaryScreen() ;

    fullScreenPix = pqscreen->grabWindow(pDesktoWidget->winId());

    //置顶
    //setWindowFlags(Qt::WindowStaysOnTopHint);
    this->show();
}

void SnapShotTemp::Dispose()
{
    if(bFinish){
        QPixmap cutPix = fullScreenPix.copy(cutRect);
        auto* snap = new SnapShot(cutPix);
        snap->move(cutRect.topLeft());
        snap->show();

        AppController::GetInstance()->AddSnapShot(snap);

        //把截图放入剪切板
        bool bUse = GlobalMgr::GetInstance()->GetUseClipBoard();
        bUse = true;
        if(bUse){
            Log<<"Input ClipBoard";
            QClipboard *clipboard = QApplication::clipboard();
            clipboard->setPixmap(cutPix);
        }
        //deleteLater();
    }
}

void SnapShotTemp::showEvent(QShowEvent *event)
{
    showFullScreen();
    //raise();
    setCursor(Qt::CrossCursor);
}

void SnapShotTemp::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(0, 0, fullScreenPix);
    painter.setPen(QColor(255,0,0));
    if(cutRect.isValid() && (cutRect.width() >0 || cutRect.height()>0))
        painter.drawRect(cutRect);

    QWidget::paintEvent(event);
}

void SnapShotTemp::mousePressEvent(QMouseEvent *event)
{
    if(Qt::LeftButton == event->button()){
        bFinish=false;
        cutRect = QRect(-1,-1,-1,-1);
        cutRect.setTopLeft(event->globalPos());
        repaint();
    }
}

void SnapShotTemp::mouseMoveEvent(QMouseEvent *event)
{
    if(!bFinish){
        cutRect.setBottomRight(event->globalPos());
        repaint();
    }
}

void SnapShotTemp::mouseReleaseEvent(QMouseEvent *event)
{
    if(Qt::LeftButton == event->button()){
        if(!bFinish){
            bFinish=true;
            cutRect.setBottomRight(event->globalPos());
            repaint();

            if(cutRect.width() <LIMIT_WIDTH || cutRect.height() < LIMIT_HEIGHT){
                bFinish=false;
            }
            //Dispose();
            AppController::GetInstance()->DeadWithSnapShot();
        }
    }
}

void SnapShotTemp::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape) {
        //delete this;
        AppController::GetInstance()->DeadWithSnapShot();
    }
}
